<template>
  <div class="income-records-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <h2>我的收入记录</h2>
          <p class="subtitle">查看您的服务收入明细</p>
        </div>
      </template>

      <!-- 统计信息 -->
      <div class="statistics-section">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">¥{{ statistics.totalAmount || '0.00' }}</div>
                <div class="stat-label">总收入</div>
              </div>
              <el-icon class="stat-icon"><Money /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">{{ statistics.totalCount || 0 }}</div>
                <div class="stat-label">服务次数</div>
              </div>
              <el-icon class="stat-icon"><User /></el-icon>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">¥{{ statistics.avgAmount || '0.00' }}</div>
                <div class="stat-label">平均收入</div>
              </div>
              <el-icon class="stat-icon"><TrendCharts /></el-icon>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input 
              v-model="searchForm.username" 
              placeholder="输入用户名" 
              clearable 
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="套餐名称">
            <el-input 
              v-model="searchForm.packageName" 
              placeholder="输入套餐名称" 
              clearable 
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="支付方式">
            <el-select 
              v-model="searchForm.paymentMethod" 
              placeholder="选择支付方式" 
              clearable 
              style="width: 120px"
            >
              <el-option label="余额支付" value="BALANCE" />
              <el-option label="支付宝" value="ALIPAY" />
              <el-option label="微信支付" value="WECHAT" />
            </el-select>
          </el-form-item>
          <el-form-item label="交易状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="选择状态" 
              clearable 
              style="width: 100px"
            >
              <el-option label="成功" :value="1" />
              <el-option label="失败" :value="0" />
              <el-option label="处理中" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 收入记录表格 -->
      <div class="table-section">
        <el-table 
          :data="records" 
          v-loading="loading"
          stripe
          style="width: 100%"
          empty-text="暂无收入记录"
        >
          <el-table-column prop="orderNo" label="订单号" width="180" show-overflow-tooltip />
          <el-table-column prop="username" label="用户" width="120">
            <template #default="{ row }">
              <div>
                <div>{{ row.username }}</div>
                <div v-if="row.nickname" class="nickname">{{ row.nickname }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="packageName" label="套餐" width="150" show-overflow-tooltip />
          <el-table-column prop="consumeAmount" label="收入金额" width="120" align="right">
            <template #default="{ row }">
              <span class="amount-text">¥{{ row.consumeAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="paymentMethod" label="支付方式" width="100">
            <template #default="{ row }">
              <el-tag :type="getPaymentMethodType(row.paymentMethod)" size="small">
                {{ getPaymentMethodName(row.paymentMethod) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusName(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="交易时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click="viewDetail(row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="收入记录详情" 
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedRecord" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号" :span="2">
            {{ selectedRecord.orderNo }}
          </el-descriptions-item>
          <el-descriptions-item label="用户">
            {{ selectedRecord.username }}
            <span v-if="selectedRecord.nickname" class="nickname">({{ selectedRecord.nickname }})</span>
          </el-descriptions-item>
          <el-descriptions-item label="预约ID">
            {{ selectedRecord.appointmentId }}
          </el-descriptions-item>
          <el-descriptions-item label="套餐名称">
            {{ selectedRecord.packageName || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="收入金额">
            <span class="amount-text">¥{{ selectedRecord.consumeAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <el-tag :type="getPaymentMethodType(selectedRecord.paymentMethod)" size="small">
              {{ getPaymentMethodName(selectedRecord.paymentMethod) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="交易状态">
            <el-tag :type="getStatusType(selectedRecord.status)" size="small">
              {{ getStatusName(selectedRecord.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="交易时间">
            {{ formatDateTime(selectedRecord.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(selectedRecord.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedRecord.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Money, User, TrendCharts } from '@element-plus/icons-vue'
import { 
  getStoreManagerIncomeRecordPage, 
  getStoreManagerIncomeStatistics 
} from '@/api/consumptionRecord'

// 响应式数据
const loading = ref(false)
const records = ref([])
const statistics = ref({})
const dateRange = ref([])
const detailDialogVisible = ref(false)
const selectedRecord = ref(null)

// 搜索表单
const searchForm = reactive({
  username: '',
  packageName: '',
  paymentMethod: '',
  status: null
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 计算平均收入
const avgAmount = computed(() => {
  if (statistics.value.totalCount && statistics.value.totalAmount) {
    return (statistics.value.totalAmount / statistics.value.totalCount).toFixed(2)
  }
  return '0.00'
})

// 页面加载时获取数据
onMounted(() => {
  loadRecords()
  loadStatistics()
})

// 加载收入记录
const loadRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    
    // 处理时间范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.startTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }
    
    const response = await getStoreManagerIncomeRecordPage(params)
    if (response.code === 200) {
      records.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取收入记录失败')
    }
  } catch (error) {
    console.error('获取收入记录失败:', error)
    ElMessage.error('获取收入记录失败')
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStatistics = async () => {
  try {
    const response = await getStoreManagerIncomeStatistics()
    if (response.code === 200) {
      statistics.value = response.data || {}
      statistics.value.avgAmount = avgAmount.value
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadRecords()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    packageName: '',
    paymentMethod: '',
    status: null
  })
  dateRange.value = []
  pagination.page = 1
  loadRecords()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadRecords()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  loadRecords()
}

// 查看详情
const viewDetail = (record) => {
  selectedRecord.value = record
  detailDialogVisible.value = true
}

// 获取支付方式类型
const getPaymentMethodType = (method) => {
  const types = {
    'BALANCE': 'primary',
    'ALIPAY': 'success',
    'WECHAT': 'warning'
  }
  return types[method] || 'info'
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  const names = {
    'BALANCE': '余额支付',
    'ALIPAY': '支付宝',
    'WECHAT': '微信支付'
  }
  return names[method] || method
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'danger',
    1: 'success',
    2: 'warning'
  }
  return types[status] || 'info'
}

// 获取状态名称
const getStatusName = (status) => {
  const names = {
    0: '失败',
    1: '成功',
    2: '处理中'
  }
  return names[status] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.income-records-container {
  padding: 20px;
}

.page-card {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.statistics-section {
  margin-bottom: 30px;
}

.stat-card {
  position: relative;
  overflow: hidden;
}

.stat-card .el-card__body {
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  font-size: 40px;
  color: #409eff;
  opacity: 0.8;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.amount-text {
  color: #67c23a;
  font-weight: bold;
}

.nickname {
  font-size: 12px;
  color: #909399;
}

.detail-content {
  padding: 10px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .income-records-container {
    padding: 12px;
  }
  
  .statistics-section .el-col {
    margin-bottom: 16px;
  }
  
  .search-section .el-form {
    display: block;
  }
  
  .search-section .el-form-item {
    display: block;
    margin-bottom: 16px;
  }
  
  .search-section .el-form-item__content {
    margin-left: 0 !important;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style> 